#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include"debug_print.h"
extern int errno;

int client(char *ip_address,int port)
{
    int fd_client_socket;
    struct sockaddr_in server_addr;
	
	//------------------- 创建socket -------------------//
	//AF_INET 		ipv4
	//SOCK_STREAM 	数据流模式
	//第三个参数protocol 一般为0
	DEBUG_PRINT("creat socket\r\n");
    if( (fd_client_socket = socket(AF_INET, SOCK_STREAM, 0)) < 0)
	{
		DEBUG_PRINT("creat socket error\r\n");
	    DEBUG_PRINT("error code:%d \r\n message: %s \r\n",errno,strerror(errno));
	   	return -1;
    }

    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(port);
	//转换ip字符串为网络字节序
    if(inet_pton(AF_INET, ip_address, &server_addr.sin_addr) < 0)
	{
		perror("ip address error\r\n");
	   	return -1;
    }

	//------------------- 连接远程服务器 -------------------//
	DEBUG_PRINT("connect server \r\n");
    if(connect(fd_client_socket, (struct sockaddr*)&server_addr, sizeof(server_addr)) != 0)
	{
	    DEBUG_PRINT("connect error\r\n");
	    DEBUG_PRINT("error code:%d \r\n message: %s \r\n",errno,strerror(errno));
	    return -1;
    }

	//------------------- 终止连接 -------------------//
    close(fd_client_socket);
    return 0;
}